<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021-05-01
 * Time: 11:31
 */
namespace app\admin\controller\system;
use app\admin\model\publicuse\PublicUse;
use app\admin\model\SystemModels;
use app\admin\model\traits\ModelHandle;
use app\admin\model\traits\TablHandle;
use app\common\controller\AdminController;
use app\Request;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;
/**
 * @ControllerAnnotation(title="模型管理")
 * Class Models
 * @package app\admin\controller\system
 */
class Models extends AdminController
{
    use \app\admin\traits\Curd;

    protected $sort = [
        'sort' => 'desc',
        'id'   => 'desc',
    ];
    protected $allowModifyFields = [
        'is_page',
        'status'
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SystemModels();
        $array = PublicUse::getConfigDir(__CLASS__);
        if(is_file(__DIR__.DIRECTORY_SEPARATOR.'field'.DIRECTORY_SEPARATOR.$array['class'].'.json')){
            $this->AllData = json_decode(file_get_contents(__DIR__.DIRECTORY_SEPARATOR.'field'.DIRECTORY_SEPARATOR.$array['class'].'.json'),true);
        }
    }
    /**
     * @NodeAnotation(title="列表")
     */
    public function index(Request $request)
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
//            echo '<pre>';
//            print_r($this->sort);
//            exit;
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            if(isset($this->AllData['field'])&&!empty($this->AllData['field'])){
                $post = PublicUse::Conversion($post,$this->AllData['field']);
            }
//            dump($post);exit;
            $bool = ModelHandle::createTable($post);
//            return $this->error($bool);
            if(!$bool){
                return $this->error('创建表失败');
            }
            try {
                $save = true;
//                $save = $this->model->save($post);
            } catch (\Exception $e) {
//                $this->error(json_encode($post,JSON_PARTIAL_OUTPUT_ON_ERROR));
                $this->error('保存失败:'.$e->getMessage());
            }
//            $this->error(json_encode($post,JSON_PARTIAL_OUTPUT_ON_ERROR));
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $newdata = PublicUse::getApp();
        $this->assign('app',$newdata);
        $this->assign('getEngineList',$this->model->getEngineList());
        $this->assign('getTabletypeList',$this->model->getTabletypeList());
        $this->assign('getTableList',$this->model->getTableList());
        $connections = config('database.connections');
        $databases = [];
        foreach ($connections as $key=>$value){
            $databases[] = $key;
        }
        $this->assign('databases',$databases);
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            if(isset($this->AllData['field'])&&!empty($this->AllData['field'])){
                $post = PublicUse::Conversion($post,$this->AllData['field']);
            }
            $bool = ModelHandle::updateTable($row->toArray(),$post);
            if(!$bool){
                return $this->error('数据更新失败');
            }
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $newdata = PublicUse::getApp();
        $this->assign('app',$newdata);
        $this->assign('row', $row);
        $this->assign('alldata',$this->AllData);
        $this->assign('getEngineList',$this->model->getEngineList());
        $this->assign('getTabletypeList',$this->model->getTabletypeList());
        $this->assign('getTableList',$this->model->getTableList());
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
//        echo '<pre>';
//        print_r($row->toArray());
//        exit;
        $bool = ModelHandle::deleteTable($row->toArray());
        if(!$bool){
            return $this->error('删除表失败');
        }
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }
    /**
     * @NodeAnotation(title="清除表内容")
     */
    public function clieartable($id){
        $row = $this->model->find($id)->toArray();
        $prefix = getDataBaseConfig('prefix');
        $table = $prefix.$row['table'];
        $sql = "truncate table `$table`";
//        dump($row);exit;
        try{
            Db::connect($row['databases'])->query($sql);
        }catch (\Exception $e){
            return $this->error('清空失败');
        }
        return $this->success('清除成功');
    }
    /**
     * @NodeAnotation(title="全表更新")
     */
    public function update_all_table(){
        $mysql = getDataBaseConfig('database');
        $qianzui = getDataBaseConfig('prefix');
        $connections = config('database.connections');
        foreach ($connections as $key=>$v){
            $sql = "select TABLE_NAME  AS 'table',TABLE_COMMENT as 'name',engine as 'engine' from information_schema.tables where table_schema='".$v['database']."'";
            $array = Db::connect($key)->query($sql);
//        dump($array);die();
            foreach ($array as $value){
                if(strpos($value['table'],'system_log')!==false){
                    continue;
                }
                $table = $value['table'];
                $tables = str_replace($qianzui,'',$table);
                $bool = TablHandle::updatetable($tables,$qianzui,$key,$v['database']);
                if(!$bool){
                    return $this->error('全表更新失败');
                }
            }
        }
        return $this->success('全表更新成功');
    }
    /**
     * @NodeAnotation(title="单表更新")
     */
    public function updateTable($id){
        $model = Db::name('system_model')
            ->where('id',$id)
            ->find();
        if(empty($model)){
            return $this->error('请输入模型');
        }
//        $qianzui = getDataBaseConfig('prefix');
        $table = $model['table'];
//        dump($model);exit;
        $bool = TablHandle::updatetable($table,'',$model['databases']);
        if(!$bool){
            return  $this->error('单表更新失败');
        }
        return  $this->success('单表更新成功');
    }
}